//
//  YTCountryCodeViewController.m
//  YiTuUserClient
//
//  Created by 石少庸 on 2017/2/21.
//  Copyright © 2017年 YiTu. All rights reserved.
//

#import "YTCountryCodeViewController.h"
#import "YTCountryCodeModel.h"
#import "YTCountryCodeCell.h"
#import "UIImage+YTExtension.h"

@interface YTCountryCodeViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableDictionary<NSString *, NSArray *> *dataDict;
@property (strong, nonatomic) NSArray<NSString *> *keyArray;
@property (strong, nonatomic) NSMutableArray<YTCountryCodeModel *> *originDataArray;
@property (strong, nonatomic) NSMutableArray<YTCountryCodeModel *> *searchDataArray;
@property (assign, nonatomic) BOOL isSearch;
@end

@implementation YTCountryCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareForInit];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self yt_changStatusBarWithStyle:UIStatusBarStyleDefault];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 初始化业务

// 请求数据
- (void)prepareForInit {
    _isSearch = NO;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 50;
    _keyArray = @[@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",
                  @"j",@"k",@"l",@"m",@"n",@"p",@"r",@"s",
                  @"t",@"w",@"x",@"y",@"z"];
    [_tableView registerNib:[UINib nibWithNibName:@"YTCountryCodeCell" bundle:nil] forCellReuseIdentifier:@"YTCountryCodeCell"];
    _dataDict = [NSMutableDictionary dictionary];
    _searchDataArray = [NSMutableArray array];
    _originDataArray = [NSMutableArray array];
    _tableView.tableFooterView = [UIView new];
    [_searchBar setBackgroundImage:[UIImage yt_imageWithColor:[UIColor groupTableViewBackgroundColor]]];
    if ([[YTUtilityManager manager] getCountryCodeCacheState]) { //有缓存
        [YTCountryCodeModelCache readObjectCompletion:^(NSArray<YTCountryCodeModel *> *codeArray) {
            _originDataArray = [codeArray copy];
            [self loadDataBase:_originDataArray cache:NO];
        }];
    } else {
        [self requestDataFromServer];
    }
}

#pragma mark - 数据处理

// 从服务请求数据
- (void)requestDataFromServer {
    [YTLoadingView show];
    [[YTNetManager manager] postWithURL:@"commons/getAreaCode" parameters:nil success:^(id response) {
        if (response) {
            NSDictionary *data = response[@"responseData"];
            _originDataArray = [[NSArray yy_modelArrayWithClass:[YTCountryCodeModel class] json:data[@"dataList"]] mutableCopy];
            [self loadDataBase:_originDataArray cache:YES];
        }
    } failure:^(NSError *error) {
        
    }];
}

/**
 数据处理以及缓存

 @param array 数据源
 @param cache 是否需要缓存
 */
- (void)loadDataBase:(NSArray<YTCountryCodeModel *> *)array
               cache:(BOOL)cache {
    for (NSString *str in _keyArray) {
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        for (YTCountryCodeModel *model in _originDataArray) {
            if ([model.firstChar isEqualToString:str]) {
                [temp addObject:model];
            }
        }
        [_dataDict setValue:temp forKey:str];
    }
    if (cache) {
        [YTCountryCodeModelCache cacheCountryCode:_originDataArray];
    }
    [YTLoadingView dismiss];
    [_tableView reloadData];
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_isSearch) {
        return _searchDataArray.count;
    } else {
        NSArray *array = _dataDict[_keyArray[section]];
        return array.count;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _isSearch ? 1 : _dataDict.allKeys.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YTCountryCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YTCountryCodeCell" forIndexPath:indexPath];
    if (_isSearch) {
        cell.model = _searchDataArray[indexPath.row];
    } else {
        cell.model = _dataDict[_keyArray[indexPath.section]][indexPath.row];
    }
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return _isSearch ? @"" : [_keyArray[section] uppercaseString];
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *str in _keyArray) {
        [array addObject:[str uppercaseString]];
    } 
    return array;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_delegate respondsToSelector:@selector(didSelectWithCountryCode:)]) {
        YTCountryCodeModel *model = _isSearch ? _searchDataArray[indexPath.row] : _dataDict[_keyArray[indexPath.section]][indexPath.row];
        [_delegate didSelectWithCountryCode:model.areaCode];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    _isSearch = YES;
    NSString *searchAssert = nil;
    if ([NSString yt_isChinese:searchBar.text]) { // 汉字
        searchAssert = [NSString stringWithFormat:@"nameChs CONTAINS '%@'", searchBar.text];
    } else {
        searchAssert = [NSString stringWithFormat:@"nameEn CONTAINS[c] '%@'", searchBar.text];
    }
    [YTCountryCodeModelCache searchObjectsWhere:searchAssert completion:^(NSArray<YTCountryCodeModel *> *searchArray) {
        _searchDataArray = [searchArray copy];
        if (_searchDataArray.count) {
            [_tableView reloadData];
        } else {
            _isSearch = NO;
            [SVProgressHUD showInfoWithStatus:@"哎呀,没有耶 *^_^*"];
        }
    }];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (!searchText.length) {
        _isSearch = NO;
        [_tableView reloadData];
    }
}

@end
